<?php

namespace app\api\controller;

use app\common\BaseHelper;
use app\lib\exception\ParameterException;

use app\admin\model\Memberlevel as MemberlevelMdl;
use app\admin\model\Member;
use app\admin\model\Membercoupon;
use app\admin\model\Coupon;
use app\admin\model\Rechargerule;
use app\admin\model\Memberlevelrecord;
use app\api\service\Memberlevel as MemberlevelService;

use think\Db;
use think\Exception;

class Memberlevel extends Base
{

    /**
     * 获取会员等级列表
     */
    public function getList()
    {
        $param = self::getHttpParam();

        if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }

        $where = [
            'status' => 1,
        ];

        $model = new MemberlevelMdl();
        $fields = '*';
        $order = 'create_date DESC';
        $list = $model->where($where)->field($fields)->order($order)->select();
        if(!$list){
            return show(config('status.ERROR_STATUS'), '没有会员等级', '没有会员等级');
        }

        foreach ($list as $item) {
            // 优惠最大的优惠券
            if($item['is_coupon'] == 1){
                // 最大 抵现金额
                $cashWhere = [
                    'id' => ['in', $item['coupon_ids']],
                    'status' => 1,
                    'end_time' => ['gt', date('Y-m-d H:i:s')],
                    'cash_amount' => [['neq', ''], ['neq', 'null'], 'and']
                ];
                $maxCash = Coupon::where($cashWhere)->field('id, coupon_type')->order('cash_amount DESC')->find();
                $maxCash && $maxCash = Coupon::formatCoupon($maxCash);
                // 最大 折扣力度
                $discountWhere = [
                    'id' => ['in', $item['coupon_ids']],
                    'status' => 1,
                    'end_time' => ['gt', date('Y-m-d H:i:s')],
                    'discount_strength' => [['neq', 0], ['neq', ''], ['neq', 'null'], 'and']
                ];
                $maxDiscount = Coupon::where($discountWhere)->field('id, coupon_type')->order('discount_strength DESC')->find();
                $maxDiscount && $maxDiscount = Coupon::formatCoupon($maxDiscount);

                /*$maxCoupons = [
                    'maxCash' => $maxCash,
                    'maxDiscount' => $maxDiscount
                ];*/
                $item['maxCash'] = $maxCash;
                $item['maxDiscount'] = $maxDiscount;
            }

            // 充值模板
            $rechargeRule = Rechargerule::where(['id' => $item['recharge_rule_id']])->find();
            if ($rechargeRule) {
                $item['recharge_rule'] = json_decode($rechargeRule['rule_json'], true);;
            }

            // 开通会员规则
            $paymentRules = json_decode($item['payment_rules'], true);
            $newPaymentRules = [];
            if ($paymentRules) {
                foreach ($paymentRules as $rule) {
                    $newPaymentRules[] = [
                        'level_id' => $item['id'],
                        'vip_cost' => $rule['vip_cost'], // 单位：分
                        'vip_time' => $rule['vip_time']
                    ];
                }
            }
            $item['payment_rules'] = $newPaymentRules;
        }

        $data = [
            'data' => $list,
            // 背景图
            'level1_bg' => 'https://' . $_SERVER['HTTP_HOST'] . '/public/static/wechat/image/memberlevel1_bg.png',
            'level2_bg' => 'https://' . $_SERVER['HTTP_HOST'] . '/public/static/wechat/image/memberlevel2_bg.png'
        ];

        return show(config('status.SUCCESS_STATUS'), self::MSG_SUCCESS, $data);
    }

    /**
     * 开通/升级会员等级
     */
    public function upgrade()
    {
        $param = self::getHttpParam();

        /*if (empty($param->memberId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员ID(memberId) 不能为空');
        }
        if (empty($param->levelId)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '会员等级ID(levelId) 不能为空');
        }
        if (empty($param->vip_cost)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '开通费用(vip_cost) 不能为空');
        }
        if (empty($param->vip_time)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '开通时间(vip_time) 不能为空');
        }
        if (empty($param->pay_method)) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '支付方式(pay_method) 不能为空');
        }
        if (!in_array($param->pay_method, [1, 2, 3])) {
            return show(config('status.ERROR_STATUS'), self::NOT_PARAM, '支付方式(pay_method) 不正确');
        }*/
        try {
            $this->checkParams($param);
        } catch (Exception $e) {
            return show(config('status.ERROR_STATUS'), $e->msg, $e->msg);
        }

        $memberId = $param->memberId;

        Db::startTrans();
        try {
            // 支付
            if ($param->pay_method == 1) {
                // 微信支付
//                $pay = new \app\api\service\weixin\MemberlevelPay();
//                return $pay->pay($param);
            } elseif ($param->pay_method == 2) {
                // 支付宝支付
//                $pay = new \app\api\service\alipay\MemberlevelPay();
//                return $pay->pay($param);
            } else {
                // 余额支付
                $pay = $this->balancePay($param);
            }

            if ($pay) {
                $model = new Member();
                $member = $model->get($memberId);
                // 获取用户详细信息
                $member = $this->getMemberInfo($member);

                Db::commit();
                return show(config('status.SUCCESS_STATUS'), '开通成功', $member);
            } else {
                Db::rollback();
                return show(config('status.ERROR_STATUS'), '开通失败', '开通失败');
            }
        } catch (Exception $e) {
            Db::rollback();
            return show(config('status.ERROR_STATUS'), self::MSG_ERROR, $e->getMessage());
        }
    }

    /**
     * 支付
     */
    public function pay(){
        $param = self::getHttpParam();

        try {
            $this->checkParams($param);
        } catch (Exception $e) {
            return show(config('status.ERROR_STATUS'), $e->msg, $e->msg);
        }
        //$memberId = $param->memberId;
        try {
            // 创建订单 - 新增开通会员记录
            $recordData = $this->createOrder($param);
            $param->order_no = $recordData['order_no'];

            // 支付
            if ($param->pay_method == 1) {
                // WeiXin Android iOS
                if ($param->device == 'WeiXin') {
                    // 微信支付
                    $pay = new \app\api\service\weixin\MemberlevelPay();
                } else {
                    // 微信APP支付
                    $pay = new \app\api\service\weixinApp\MemberlevelPay();
                }

                return $pay->pay($param);
            } elseif ($param->pay_method == 2) {
                // 支付宝支付
                $pay = new \app\api\service\alipay\MemberlevelPay();

                return $pay->pay($param);
            }
        } catch (Exception $e) {
            return show(config('status.ERROR_STATUS'), isset($e->msg) ? $e->msg : $e->getMessage(), isset($e->msg) ? $e->msg : $e->getMessage());
        }
    }

    /**
     * 余额支付
     */
    protected function balancePay($param){
        Db::startTrans();
        try {
            $model = new Member();
            $member = $model->get($param->memberId);
            if($member['balance'] < $param->vip_cost){
                throw new ParameterException([
                    'msg' => '用户余额不够'
                ]);
            }

            // 创建订单 - 新增开通会员记录
            $recordData = $this->createOrder($param);
            $orderNo = $recordData['order_no'];

            // 开通成功后更新会员相关信息
            $result = MemberlevelService::updateMember($param);
            if ($result['code'] != 1) {
                Db::rollback();
                throw new ParameterException([
                    'msg' => $result['msg']
                ]);
            }

            // 更新订单状态
            $orderRes = \app\admin\model\Memberlevelrecord::where('order_no', $orderNo)->update(['status' => 1, 'pay_date' => date('Y-m-d H:i:s')]);
            if($orderRes === false){
                Db::rollback();
                throw new ParameterException([
                    'msg' => '更新订单状态失败'
                ]);
            }

            Db::commit();
            return true;
        } catch (Exception $e) {
            Db::rollback();
            throw new ParameterException([
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 创建订单 - 新增开通会员记录
     */
    protected function createOrder($param){
        try {
            $openTime = date('Y-m-d H:i:s', time());
            $endTime = date('Y-m-d H:i:s', strtotime($openTime) + 3600 * 24 * 30 * $param->vip_time);
            $recordData = [
                //'id' => BaseHelper::getUUID(),
                'create_date' => date('Y-m-d H:i:s'),
                'order_no' => create_order_sn(),
                'member_id' => $param->memberId,
                'member_level_id' => $param->levelId,
                'level_time' => $param->vip_time * 30, // 单位：天
                'open_time' => $openTime,
                'end_time' => $endTime,
                //'money' => $param->vip_cost * 100,
                'money' => $param->vip_cost,
                'pay_method' => $param->pay_method,
            ];

            $recordRes = Memberlevelrecord::insert($recordData);
            if($recordRes === false){
                throw new ParameterException([
                    'msg' => '创建订单失败'
                ]);
            }

            return $recordData;
        } catch (Exception $e) {
            throw new ParameterException([
                'msg' => '创建订单失败'
            ]);
        }
    }

    // 检查参数
    protected function checkParams($param){
        if (empty($param->device)) {
            throw new ParameterException([
                'msg' => '设备类型(device) 不能为空'
            ]);
        }
        if (empty($param->memberId)) {
            throw new ParameterException([
                'msg' => '会员ID(memberId) 不能为空'
            ]);
        }
        if (empty($param->levelId)) {
            throw new ParameterException([
                'msg' => '会员等级ID(levelId) 不能为空'
            ]);
        }
        if (empty($param->vip_cost)) {
            throw new ParameterException([
                'msg' => '开通费用(vip_cost) 不能为空'
            ]);
        }
        if (empty($param->vip_time)) {
            throw new ParameterException([
                'msg' => '开通时间(vip_time) 不能为空'
            ]);
        }
        if (empty($param->pay_method)) {
            throw new ParameterException([
                'msg' => '支付方式(pay_method) 不能为空'
            ]);
        }
        if (!in_array($param->pay_method, [1, 2, 3])) {
            throw new ParameterException([
                'msg' => '支付方式(pay_method) 不正确'
            ]);
        }
    }
}